package cn.hzc.fortess.system.eventbus;

import cn.hzc.fortess.system.dao.LogDao;
import com.google.common.eventbus.Subscribe;

import cn.hzc.fortess.system.entity.BizLog;
import cn.hzc.fortess.system.entity.LoginLog;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

@Service
public class LogSubscriber {

    @Autowired
    LogDao logDao;

    @Subscribe
    public void loginLogger(LoginLogEvent event) {
        LoginLog logger = new LoginLog();
        BeanUtils.copyProperties(event, logger);
        logger.setCreateTime(new Date());
        logDao.saveLoginLog(logger);
    }

    @Subscribe
    public void bizLogger(BizLogEvent event) {
        BizLog logger = new BizLog();
        BeanUtils.copyProperties(event, logger);
        logger.setCreateTime(new Date());
        logger.setLogStatus("SUCCESS");

        logger.setLogName(event.getException() != null ? "EXCEPTION" : "BIZ");
        if (event.getLogName() != null) {
            logger.setLogName(event.getLogName());
        }
        if (event.getException() != null) {
            logger.setLogDetail(getExceptionMsg(event.getException()));
            logger.setLogStatus("EXCEPTION");
        }
        logDao.saveBizLog(logger);
    }

    private static String getExceptionMsg(Throwable e) {
        StringWriter sw = new StringWriter();
        try {
            e.printStackTrace(new PrintWriter(sw));
            return sw.getBuffer().toString().replaceAll("\\$", "T");
        } finally {
            try {
                sw.close();
            } catch (IOException e1) {
            }
        }
    }

}
